import random
import uuid

from django.http import HttpResponse
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from verifications import constants
from verifications.serializers import ImageCodeCheckSerializer
from zscool.tools.captcha.captcha import captcha
from zscool.tools.dysms_python.demo_sms_send import send_sms


class ImageCodeView(APIView):
    """图片验证码"""

    def get(self, request, image_code_id):
        # 生成验证码图片
        text, image = captcha.generate_captcha()
        # 保存真实值到redis中
        redis_conn = get_redis_connection("verify_codes")
        redis_conn.setex('img_%s' % image_code_id,  constants.IMAGE_CODE_REDIS_EXPIRES, text)
        # 返回图片
        return HttpResponse(image, content_type='images/jpg')


class SMSCodeView(GenericAPIView):
    """
    短信验证码
    传入参数：nmobile, image_code_id, text
    """
    serializer_class = ImageCodeCheckSerializer

    def get(self, request):
        # 校验参数  序列化器完成
        serializer = self.get_serializer(data=request.query_params)   # 有data　是校验。　　无data　是序列化
        serializer.is_valid(raise_exception=True)  # raise_exceptions=True 验证失败时抛出异常

        req_data = request.query_params
        mobile = req_data['mobile']
        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        print(sms_code)
        # 保存真实值 、保存发送记录
        redis_conn = get_redis_connection('verify_codes')
        # redis_conn.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # redis_conn.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # redis的管道
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        # 让管道执行上面的命令操作
        pl.execute()

        data = {
            "message":sms_code,
        }

        # return Response(data)   # 打开发送短信需要把这个注释掉


# 把这里注释掉的内容打开即可发送短信，需要替换阿里短信模板里面的ACCESS_KEY_ID,ACCESS_KEY_SECRET,为自己的

        # 发送短信
        try:
            __business_id = uuid.uuid1()
            # print(__business_id)
            params = "{\"code\":\"%s\"}" %sms_code
            sms_status = send_sms(__business_id, "%s" % mobile, "zscool博客", "SMS_153327250", params)
            # 字节转字符串
            sms_status = sms_status.decode()
            # 字符串转字典
            sms_status = eval(sms_status)
            # print(sms_status["Code"])

        except Exception as e:
            # logger.error("发送验证码短信[异常][ mobile: %s, message: %s ]" % (mobile, e))
            return Response({'message': 'failed'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            if sms_status["Code"] == "OK":
                # logger.info("发送验证码短信[正常][ mobile: %s ]" % mobile)
                return Response({'message': '短信发送成功'})

            else:
                # logger.warning("发送验证码短信[失败][ mobile: %s ]" % mobile)
                return Response({'message': '短信发送失败'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


